#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <sys/socket.h>
//#include <netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>

#include <time.h>
#include <errno.h>

#define MAXLINE 1024


void check(int ret){
	if(ret<0){
		fprintf(stderr,"error :%d %s\n",errno,strerror(errno));
		exit(0);
	}
}
int main(){
	int listenfd,connfd;
	struct sockaddr_in servaddr;
	char buff[MAXLINE];
	time_t ticks;
	
	listenfd=socket(AF_INET,SOCK_STREAM,0);
	
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family=AF_INET;
	servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
	servaddr.sin_port=htons(13);
	
	int ret;
	ret=bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
	check(ret);
	ret=listen(listenfd,1);
	check(ret);
	printf("listenfd:%d\n",listenfd);
	
	struct sockaddr_in clientaddr;
	int count=3;
	
	for(;;){
		count--;
		if(count==0)
			break;
		bzero(&clientaddr,sizeof(clientaddr));
		unsigned int clen=sizeof(clientaddr);
		connfd=accept(listenfd,(struct sockaddr *)&clientaddr,&clen);
		//connfd=accept(listenfd,(struct sockaddr *)NULL,NULL);
		//if(connfd>0){
			printf("client connected %d,  %s %d\n",connfd,inet_ntoa(clientaddr.sin_addr.s_addr),clientaddr.sin_port);
			ticks=time(NULL);
			snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
			write(connfd,buff,strlen(buff));

			close(connfd);
		//}
		
	}
	exit(0);
}